//
//  ViewController.m
//  InDoorNav
//
//  Created by 刘建峰 on 16/10/10.
//  Copyright © 2016年 chenling. All rights reserved.
//

#import "IndoorMapViewController.h"
#import "IndoorMapScrollView.h"
#import "IndoorMapViewNew.h"
#import "SampleFileInfo.h"
#import "SVGKSourceLocalFile.h"
#import "MyNavigationViewController.h"
#import "IndoorFloorTableViewCell.h"
#import <CoreLocation/CoreLocation.h>
#import "WaveAnimationView.h"
#import "NSFileHandle+readLine.h"

static NSString * cellIndentifier = @"IndoorFloorTableViewCell";

#define currentAltitude 275;
@interface IndoorMapViewController ()<IndoorMapViewNewDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,CLLocationManagerDelegate>{
    BOOL _allowSwipeGesture;
    IndoorMapScrollView *indoorMapScrollView;
    NSTimer *myTimer;//定时器
    
    BOOL  animationTimer;
}
@property (nonatomic,strong)WaveAnimationView *waveAnimationView;

@property (nonatomic ,strong) CLLocationManager *mgr;
@property (weak, nonatomic) IBOutlet UIImageView *compasspointer;//指南针
@property (weak, nonatomic) IBOutlet UIButton *maskButton;
@property (weak, nonatomic) IBOutlet UIView *searchBackView;
@property (weak, nonatomic) IBOutlet UITextField *searchTextfield;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *noticeView;
@property(nonatomic,strong) NSMutableArray* sectionNames;
@property(nonatomic,strong) NSMutableDictionary* itemArraysBySectionName;
@property(nonatomic,assign)NSInteger time;
@property(nonatomic,assign)NSInteger currentFloor;//当前实际楼层
@property(nonatomic,assign)NSInteger endFloor;//目的地楼层(切换的楼层)
@property(nonatomic,strong)AStarItem * EndItem;//目的地楼层坐标

@property(nonatomic,assign)BOOL ifBack;//返回

@property (weak, nonatomic) IBOutlet UIButton *floorButton;
@property (weak, nonatomic) IBOutlet UIView *floorView;
@property (weak, nonatomic) IBOutlet UITableView *floorTableView;

@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UIButton *storeAddressLabel;
@property (weak, nonatomic) IBOutlet UILabel *storeNameLabel;
@property(nonatomic,assign)NSInteger floorOrFaciality;//2设施  3搜索店铺  4没有设施切换其他楼层时选楼层

@property(nonatomic,strong)NSArray * storePointArray;
@property(nonatomic,assign)BOOL specialNeed;
@property(nonatomic,assign)CGPoint specialPoint;

//////没有设施时用
@property(nonatomic,strong)NSMutableArray * haveFacialityArray;///有设施的楼层
@property(nonatomic,strong)NSMutableArray * haveFacialityPointArray;//有设施的楼层上的设施坐标


@end

@implementation IndoorMapViewController

- (void)viewWillDisappear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    //强制旋转竖屏
    [self forceOrientationPortrait];
    MyNavigationViewController *navi = (MyNavigationViewController *)self.navigationController;
    navi.interfaceOrientation = UIInterfaceOrientationPortrait;
    navi.interfaceOrientationMask = UIInterfaceOrientationMaskPortrait;
    
    //设置屏幕的转向为竖屏
    [[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}

- (void)viewWillAppear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    
    //强制旋转横屏
    [self forceOrientationLandscape];
    MyNavigationViewController *navi = (MyNavigationViewController *)self.navigationController;
    navi.interfaceOrientation =   UIInterfaceOrientationLandscapeLeft;
    navi.interfaceOrientationMask = UIInterfaceOrientationMaskLandscapeLeft;
    
    //强制翻转屏幕，Home键在右边。
    [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(havaNoFacilities) name:@"havaNoFacilities" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(havaAddEndImage) name:@"havaAddEndImage" object:nil];
    
    _time = 0;
    _endFloor = 3;
    _ifBack = NO;
    _currentFloor = 3;
    // Do any additional setup after loading the view.
    self.rightSwipeGesture.enabled = NO;
    [self initViewLayout];
    [self getStoresNames:@"3"];
}

- (void)initViewLayout{
    
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.searchBackView];
    [self adaptiveViewLayout:self.noticeView];
    [self adaptiveViewLayout:self.addressView];
    [self adaptiveViewLayout:self.floorView];
    
    _floorButton.layer.masksToBounds = YES;
    _floorButton.layer.cornerRadius = 16*VerticalRatio();
    
    _floorTableView.layer.cornerRadius = 4*VerticalRatio();
    
    [_floorTableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _floorTableView.dataSource = self;
    _floorTableView.delegate = self;
    
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    _searchBackView.layer.borderWidth = 1;
    _searchBackView.layer.borderColor = kGetColor(235, 235, 235).CGColor;
    _searchBackView.layer.cornerRadius = 15*VerticalRatio();
    
    _searchTextfield.delegate = self;
    
    _noticeView.layer.cornerRadius = 10*VerticalRatio();

    
    _mgr = [[CLLocationManager alloc] init];
    self.mgr.delegate = self;
    [self.mgr startUpdatingHeading];
    
    indoorMapScrollView = [[IndoorMapScrollView alloc] initWithFrame:flexibleFrame(CGRectMake(60, 35, 430, 245), NO)];
    indoorMapScrollView.mapViewNew.delegate = self;
    indoorMapScrollView.floor = @"3";//设置寻路路线集合文件名
    indoorMapScrollView.mapViewNew.floor = @"3";//设置楼层设施文件路径
    [indoorMapScrollView.mapViewNew loadSVGFrom:[SampleFileInfo sampleFileInfoWithFilename:[NSString stringWithFormat:@"masp%@.svg",@"3"]].source rangeString:[NSString stringWithFormat:@"/masp%@.svg",@"3"]];//设置svg文件名
    [self.view insertSubview:indoorMapScrollView belowSubview:_searchBackView];
    
    ///水波点击效果
    _waveAnimationView = [[WaveAnimationView alloc] initWithFrame:CGRectMake(-1000, -1000, 4 ,4)];
    _waveAnimationView.backgroundColor = [UIColor clearColor];
    [indoorMapScrollView insertSubview:_waveAnimationView aboveSubview:indoorMapScrollView.mapViewNew];
    

    //定时器
    myTimer=[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(userToNextArea:) userInfo:nil repeats:YES];

}

- (IBAction)back:(id)sender {
    _ifBack = YES;
    
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark === 查询当前楼层所有店铺名称
- (void)getStoresNames:(NSString *)floor{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:floor forKey:@"mstoStair"];
    [dic setObject:@"" forKey:@"search"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryShopRankingMap withHttpType:@"POST" withTag:SX_SX_queryStoreNames];
}

#pragma mark === =搜索

- (IBAction)searchHandel:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        _searchBackView.hidden = NO;
    }else{
        _searchBackView.hidden = YES;
    }
}

#pragma mark  ==== uitextfieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self hideKeyBoard];
    _storePointArray = [NSArray array];
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"" forKey:@"mstoStair"];
    [dic setObject:_searchTextfield.text forKey:@"search"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryShopRankingMap withHttpType:@"POST" withTag:SX_SX_queryShopRankingMap];
   
    return YES;
}

#pragma mark - CLLocationManagerDelegate
// 当获取到用户方向时就会调用
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    CGFloat angle = (newHeading.magneticHeading * M_PI-90*M_PI)/180;
    self.compasspointer.transform = CGAffineTransformMakeRotation(-angle);
  
}

#pragma mark === 没有设施
- (void)havaNoFacilities{
    NSArray * noticeArray = [[NSUserDefaults standardUserDefaults]objectForKey:@"havaNoFacilities"];//第一个是设施的下标   第二个是设施的名字

    NSString * name = [[Common stringFromData:noticeArray[1]]substringFromIndex:1];
    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"当前楼层没有%@,是否去其他楼层?",name] delegate:self cancelButtonTitle:@"确认" otherButtonTitles:@"取消", nil];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSArray * noticeArray = [[NSUserDefaults standardUserDefaults]objectForKey:@"havaNoFacilities"];//第一个是设施的下标   第二个是设施的名字
    NSInteger facialityFlag = [noticeArray[0]floatValue];
    _haveFacialityArray = [NSMutableArray array];//有设施的楼层
    _haveFacialityPointArray = [NSMutableArray array];//设施楼层坐标数组
    if (buttonIndex == 0) {//没有设施查询附近楼层设施
        for (int f=1; f<5; f++) {
            NSMutableArray * facilityArray = [self fetchFacilityPoint:[NSString stringWithFormat:@"设施%d",f]];
                NSArray * array = facilityArray[facialityFlag-1];
            AStarItem * item = array[0];

            if (array.count>=1 && item.id_row>0&&item.id_col>0) {
                [_haveFacialityArray addObject:[NSString stringWithFormat:@"%d",f]];
                [_haveFacialityPointArray addObject:array];
            }
            
        }
        
        _floorOrFaciality = 4;
        _tableView.hidden = NO;
        _maskButton.hidden = NO;
        [_tableView reloadData];
        
    }
    
}

#pragma mark ======= 查找商城设施点集合
- (NSMutableArray *)fetchFacilityPoint:(NSString *)filePath
{
    NSMutableArray *results = [[NSMutableArray alloc] init];
    NSString *path = [[NSBundle mainBundle] pathForResource:filePath ofType:@"txt"];
    
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    
    NSData *lineData;
    
    while ((lineData = [fileHandle readLineWithDelimiter:@"\n"]))
    {
        NSString *lineString = [[NSString alloc] initWithData:lineData encoding:NSUTF8StringEncoding];
        
        //#号为注释
        if ([lineString characterAtIndex:0] == '#')
        {
            continue;
        }
        NSString *replaceStr = [lineString stringByReplacingOccurrencesOfString:@"(" withString:@"{"];
        NSString *replaceStr1 = [replaceStr stringByReplacingOccurrencesOfString:@")" withString:@"}"];
        
        NSArray *array = [replaceStr1 componentsSeparatedByString:@"||"];
        for (int j = 0; j<array.count; j++) {
            NSString * replaceStr = array[j];
            NSArray * Array = [replaceStr componentsSeparatedByString:@";"];
            NSMutableArray *points = [[NSMutableArray alloc] init];
            if (Array) {
                
                for (int i = 0; i < Array.count; i++) {
                    
                    NSString *pointStr = [Array objectAtIndex:i];
                    pointStr = [pointStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                    pointStr = [pointStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    
                    if (![points containsObject:pointStr])
                    {
                        [points addObject:pointStr];
                    }
                    
                }
            }
            
            NSMutableArray * arr = [NSMutableArray array];
            for (NSString *pointStr in points) {
                
                AStarItem *item = [[AStarItem alloc] init];
                
                CGPoint point = CGPointFromString(pointStr);
                
                //转换坐标系
                //        point.y = 760 - point.y;
                //
                //        point.x = (point.x / 100.0f  - OFFSET_X) * RATIO;
                //        point.y = (MAP_HEIGHT - point.y / 100.0f) * RATIO + _offset_y;
                
                [item setPos:point.x row:point.y];
                
                //结点集合
                [arr addObject:item];
            }
            [results addObject:arr];
        }
    }
    
    return results;
}


#pragma mark === 特殊需要重置终点图片
- (void)havaAddEndImage{
    if (_specialNeed) {
        _specialNeed = NO;
        if (_EndItem&&_floorOrFaciality==4) {
            indoorMapScrollView.endUserPoint = CGPointMake(_EndItem.id_col, _EndItem.id_row);
            indoorMapScrollView.mapViewNew.endImage.frame = CGRectMake(_EndItem.id_col-20, _EndItem.id_row-50, 40, 50);
            [indoorMapScrollView touchEndPosition];
            _tableView.hidden = YES;
            _maskButton.hidden = YES;
        }else{
            indoorMapScrollView.mapViewNew.endImage.frame = CGRectMake(_specialPoint.x-20, _specialPoint.y-50, 40, 50);
            indoorMapScrollView.endUserPoint = _specialPoint;
            [indoorMapScrollView touchEndPosition];
        }
    }
   
}

#pragma mark === 隐藏弹出视图
- (IBAction)maskButtonHidden:(id)sender {
    _tableView.hidden = YES;
    _floorButton.selected = NO;
    _noticeView.hidden = YES;
    _maskButton.hidden = YES;
}
#pragma mark === 确认取消导航
- (IBAction)sureCancle:(id)sender {
    _EndItem = nil;
    _endFloor = _currentFloor;
    indoorMapScrollView.endUserPoint = indoorMapScrollView.startUserPoint;
    indoorMapScrollView.mapViewNew.endImage.frame = CGRectMake(0, 0, 0, 0);
    [indoorMapScrollView touchEndPosition];
    
    _maskButton.hidden = YES;
    _noticeView.hidden = YES;
    _floorButton.selected = NO;
    
    UILabel * label = [self.view viewWithTag:50];
    label.hidden = YES;
    
    [self getStoresNames:[NSString stringWithFormat:@"%ld",_currentFloor]];
}
#pragma mark === 不取消导航
- (IBAction)noCancle:(id)sender {
    _noticeView.hidden = YES;
    _maskButton.hidden = YES;
}
#pragma mark ==== 修改楼层
- (IBAction)changeFloor:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        if (_EndItem) {
            _noticeView.hidden = NO;
            _maskButton.hidden = NO;
        }else{
            _floorView.hidden = NO;
        }
    }else{
        _floorView.hidden = YES;
    }
    
}

#pragma mark ===== 随时刷新用户位置
-(void)userToNextArea:(id)sender{
    if (_ifBack) {
        return;
    }
    _time++;
    [self getIndoorMapData];
}
//得到定位数据
- (void)getIndoorMapData{
    //    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    //    [dic setObject:[self deviceIPAdress] forKey:@"ip"];
    //    [shareApi  requestOperationWithDic:dic withPath:SX_IP withHttpType:@"GET" withTag:SX_kADBannerTag];
    MyPositon *position = [[MyPositon alloc] init];
    float  x =125;
    float  y= 165;
    [_floorButton setTitle:@"3F" forState:UIControlStateNormal];
    indoorMapScrollView.startUserPoint = CGPointMake(x, y);
    position.point = CGPointMake(x, y);
    indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(x-20, y-50, 40, 50);
    [indoorMapScrollView touchEndPosition];
    


}

- (NSString *)deviceIPAdress {
    NSString *address = @"an error occurred when obtaining ip address";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    success = getifaddrs(&interfaces);
    
    if (success == 0) { // 0 表示获取成功
        
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    freeifaddrs(interfaces);
    
    return address;
}


#pragma mark == 查找当前楼层到电梯最近的路径(跨楼层导航)
- (void)checkCloserWaySameFloor{
    _floorOrFaciality = 2;
    [_tableView reloadData];
    _tableView.hidden = NO;
    _maskButton.hidden = NO;
}


#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _floorTableView) {
        return 4;
    }else{
        if(_floorOrFaciality == 2){
            return 4;
        }else if (_floorOrFaciality==3){
            return _storePointArray.count;
        }else if (_floorOrFaciality==4){
            return _haveFacialityArray.count;
        }
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_floorTableView) {
        return 30*VerticalRatio();
    }else{
        return 40*VerticalRatio();
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (tableView == _floorTableView) {
        IndoorFloorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (!cell) {
            cell = [[IndoorFloorTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        NSArray * array = @[@"4F 美食娱乐",@"3F 床上用品",@"2F 女士服饰",@"1F 男士服饰"];

        NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:array[indexPath.row]];
        [str addAttribute:NSForegroundColorAttributeName value:kGetColor(250, 133, 10) range:NSMakeRange(0, 2)];
        cell.floorName.attributedText = str;
        
        return cell;
    }else{
        static NSString *cellIdentify = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify ];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        }
        for (UIView * view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                [view removeFromSuperview];
            }
        }
        NSArray * array = [NSArray array];

        if(_floorOrFaciality==2){
            array = @[@"楼梯",@"扶梯",@"观光电梯",@"升降电梯"];
        }else if(_floorOrFaciality==3){
            array = _storePointArray;
        }else if(_floorOrFaciality==4){
            array = [_haveFacialityArray copy];
        }
        UILabel * label = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 40), NO)];
        label.font = [UIFont systemFontOfSize:15*VerticalTexeRatio()];
        label.textAlignment = NSTextAlignmentCenter;

        if (_floorOrFaciality==2) {
            label.text = array[indexPath.row];
        }else if (_floorOrFaciality==3) {
            label.text = [NSString stringWithFormat:@"%@(%@楼)",[Common stringFromData:array[indexPath.row ][@"mstoName"]],[Common stringFromData:array[indexPath.row ][@"mstoStair"]]];
        }else if (_floorOrFaciality==4){
            label.text = [NSString stringWithFormat:@"去%@楼",[Common stringFromData:array[indexPath.row]]];
        }
    
        UILabel * line = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 39, 320, 1), NO)];
        line.backgroundColor = kGetColor(229, 229, 229);
        
        
        [cell addSubview:label];
        [cell addSubview:line];
        
        return cell;

    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == _floorTableView) {
    NSArray * floorArray = @[@"1F",@"2F",@"3F",@"4F"];
    NSArray * floorNumArray = @[@3,@2,@1,@0];
    NSInteger index =[floorNumArray[indexPath.row]integerValue];
    [_floorButton setTitle:floorArray[index] forState:UIControlStateNormal];
    NSString * floor = [NSString stringWithFormat:@"%ld",index+1];
    if (_endFloor == index+1) {
        _floorButton.selected = NO;
        _floorView.hidden = YES;
        _maskButton.hidden = YES;
        return;
    }
    _endFloor = index+1;
    
    indoorMapScrollView.endUserPoint = indoorMapScrollView.startUserPoint;
    indoorMapScrollView.mapViewNew.endImage.frame = CGRectMake(-1000, 0, 40, 50);
    [indoorMapScrollView touchEndPosition];//切换楼层隐藏pathView
    
    if (_endFloor !=_currentFloor) {
        indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(-1000, 0, 40, 50);
    }
    
    
    indoorMapScrollView.floor = floor;//设置寻路路线集合文件名
    [indoorMapScrollView.mapViewNew clearSubviews];
    UILabel * navLabe = [self.view viewWithTag:50];
    [navLabe removeFromSuperview];
    indoorMapScrollView.mapViewNew.floor = floor;//设置楼层设施文件路径
    [indoorMapScrollView.mapViewNew loadSVGFrom:[SampleFileInfo sampleFileInfoWithFilename:[NSString stringWithFormat:@"masp%@.svg",floor]].source rangeString:[NSString stringWithFormat:@"/masp%@.svg",floor]];//设置svg文件名
        [self getStoresNames:[NSString stringWithFormat:@"%ld",index+1]];
        _floorButton.selected = NO;
        _floorView.hidden = YES;
        _addressView.hidden = YES;
    }else{
        NSInteger index = indexPath.row;
        if(_floorOrFaciality==2){
        NSMutableArray * facilityArray = [indoorMapScrollView.mapViewNew fetchFacilityPoint:[NSString stringWithFormat:@"设施%ld",_currentFloor]];
        NSArray * facArray = facilityArray[index];

        CGPoint userCenter = indoorMapScrollView.mapViewNew.userImage.center;
        
        float k = 0;
        int j = 0;
        for (int i =0; i<facArray.count; i++) {
            AStarItem * item = facArray[i];
            float a = sqrt((item.id_col-userCenter.x)*(item.id_col-userCenter.x)+(item.id_row-userCenter.y)*(item.id_row-userCenter.y));
            if (a<k || i==0) {
                k=a;
                j=i;
            }
        }
        
        AStarItem * item = facArray[j];
        indoorMapScrollView.endUserPoint = CGPointMake(item.id_col, item.id_row);
        indoorMapScrollView.mapViewNew.endImage.frame = CGRectMake(item.id_col-20, item.id_row-50, 40, 50);
        [indoorMapScrollView touchEndPosition];
            
        _tableView.hidden = YES;
        _maskButton.hidden = YES;
            
        [self getStoresNames:[NSString stringWithFormat:@"%ld",_currentFloor]];
            
    }else if (_floorOrFaciality==3){
        NSString * pointStr = [Common stringFromData:_storePointArray[indexPath.row][@"mstoPosition"]];
        NSArray * xyArray = [pointStr componentsSeparatedByString:@","];
        CGFloat x = [[[Common stringFromData:xyArray[0]]substringFromIndex:1]floatValue];
        CGFloat y = [[[Common stringFromData:xyArray[1]]substringToIndex:[Common stringFromData:xyArray[1]].length-1]floatValue];
        CGPoint point =CGPointMake(x, y);
        
        NSInteger chosefloor =[_storePointArray[indexPath.row][@"mstoStair"] integerValue];
        if (chosefloor ==_currentFloor) {//点击当前楼层店铺
            if (_endFloor !=_currentFloor) {
                _endFloor = _currentFloor;
                [indoorMapScrollView.mapViewNew clearSubviews];
                indoorMapScrollView.floor = [NSString stringWithFormat:@"%ld",chosefloor];//设置寻路路线集合文件名
                indoorMapScrollView.mapViewNew.floor = [NSString stringWithFormat:@"%ld",chosefloor];//设置楼层设施文件路径
                [indoorMapScrollView.mapViewNew loadSVGFrom:[SampleFileInfo sampleFileInfoWithFilename:[NSString stringWithFormat:@"masp%ld.svg",chosefloor]].source rangeString:[NSString stringWithFormat:@"/masp%ld.svg",chosefloor]];//设置svg文件名
                
                [self getStoresNames:[NSString stringWithFormat:@"%ld",chosefloor]];
            }
            
            NSArray * floorArray = @[@"1F",@"2F",@"3F",@"4F"];
            [_floorButton setTitle:floorArray[chosefloor-1] forState:UIControlStateNormal];
        
            _specialNeed = YES;
            _specialPoint = point;
          
            _tableView.hidden = YES;
            _maskButton.hidden = YES;
        }else{//点击其他楼层店铺
            _EndItem = nil;
            _tableView.hidden = YES;
            _maskButton.hidden = YES;
            _endFloor = chosefloor;
            [self touchPosition:point];
        }
        
    }else if (_floorOrFaciality == 4){
        _endFloor = [_haveFacialityArray[indexPath.row]integerValue];
        _EndItem = (AStarItem *)_haveFacialityPointArray[indexPath.row][0];
        
        NSString * floor = [NSString stringWithFormat:@"%ld",_currentFloor];
        NSArray * array = @[@"1F",@"2F",@"3F",@"4F"];
        [_floorButton setTitle:array[_currentFloor-1] forState:UIControlStateNormal];
        
        indoorMapScrollView.floor = floor;//设置寻路路线集合文件名
        [indoorMapScrollView.mapViewNew clearSubviews];
        UILabel * navLabe = [self.view viewWithTag:50];
        [navLabe removeFromSuperview];
        indoorMapScrollView.mapViewNew.floor = floor;//设置楼层设施文件路径
        [indoorMapScrollView.mapViewNew loadSVGFrom:[SampleFileInfo sampleFileInfoWithFilename:[NSString stringWithFormat:@"masp%@.svg",floor]].source rangeString:[NSString stringWithFormat:@"/masp%@.svg",floor]];//设置svg文件名
        
        if (_endFloor == _currentFloor) {
            _specialNeed = YES;
            [self getStoresNames:[NSString stringWithFormat:@"%ld",_currentFloor]];
        }else{
            [self checkCloserWaySameFloor];
        }
    }
        
    }
 
}



#pragma mark ==== 目的地楼层点击事件 IndoorMapViewNewDelegate
- (void)touchPosition:(CGPoint)point{
    
    if (_endFloor!=_currentFloor) {
        if (!_EndItem) {
            _EndItem = [[AStarItem alloc]init];
            [_EndItem setPos:point.x row:point.y];
            
            NSString * floor = [NSString stringWithFormat:@"%ld",_currentFloor];
            NSArray * array = @[@"1F",@"2F",@"3F",@"4F"];
            [_floorButton setTitle:array[_currentFloor-1] forState:UIControlStateNormal];

            indoorMapScrollView.floor = floor;//设置寻路路线集合文件名
            [indoorMapScrollView.mapViewNew clearSubviews];
            UILabel * navLabe = [self.view viewWithTag:50];
            [navLabe removeFromSuperview];
            indoorMapScrollView.mapViewNew.floor = floor;//设置楼层设施文件路径
            [indoorMapScrollView.mapViewNew loadSVGFrom:[SampleFileInfo sampleFileInfoWithFilename:[NSString stringWithFormat:@"masp%@.svg",floor]].source rangeString:[NSString stringWithFormat:@"/masp%@.svg",floor]];//设置svg文件名
            
            [self checkCloserWaySameFloor];
        }else{
            _noticeView.hidden = NO;
            _maskButton.hidden = NO;
        }
    }else{
        indoorMapScrollView.endUserPoint = point;
        indoorMapScrollView.mapViewNew.endImage.frame = CGRectMake(point.x-20, point.y-50, 40, 50);
        [indoorMapScrollView findShortestPath:indoorMapScrollView.startUserPoint end:point filePath:[NSString stringWithFormat:@"masp%ld",_currentFloor]];
        
        float k = 0;
        int j = 0;
        for (int i = 0; i<_storePointArray.count; i++) {
            NSString * pointStr = [Common stringFromData:_storePointArray[i][@"mstoPosition"]];
            NSArray * xyArray = [pointStr componentsSeparatedByString:@","];
            CGFloat x = [[[Common stringFromData:xyArray[0]]substringFromIndex:1]floatValue];
            CGFloat y = [[[Common stringFromData:xyArray[1]]substringToIndex:[Common stringFromData:xyArray[1]].length-1]floatValue];
            
            
            float a = sqrt((point.x-x)*(point.x-x)+(point.y-y)*(point.y-y));
            if (i==0) {
                k=a;
            }else{
                if (a<k) {
                    k=a;
                    j=i;
                }
            }
        }
       
        _storeNameLabel.text = [Common stringFromData:_storePointArray[j][@"mstoName"]];
        [_storeAddressLabel setTitle:[Common stringFromData:_storePointArray[j][@"mstoAddress"]] forState:UIControlStateNormal];
        _addressView.hidden = NO;
        
        ///水波点击效果
        _waveAnimationView.center =CGPointMake(point.x*indoorMapScrollView.zoomScale, point.y*indoorMapScrollView.zoomScale);
        [_waveAnimationView setNeedsDisplay];
    }
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{

    if (tag==SX_kADBannerTag){
        MyPositon *position = [[MyPositon alloc] init];
        float x = [database[@"posX"] floatValue];
        float y = [database[@"posY"] floatValue];
        float locID = [database[@"locID"] floatValue];
        NSString *locName = [NSString stringWithFormat:@"%@",database[@"locName"]];
        if([locName isEqualToString:@"floor3"]){
            
            _currentFloor =3;
            if (_endFloor !=_currentFloor) {
                _endFloor = 3;
                //切换三楼
                [_floorButton setTitle:@"3F" forState:UIControlStateNormal];
                NSString * floor = [NSString stringWithFormat:@"3"];
                
                indoorMapScrollView.endUserPoint = indoorMapScrollView.startUserPoint;
                indoorMapScrollView.mapViewNew.endImage.frame = CGRectMake(-1000, 0, 40, 50);
                [indoorMapScrollView touchEndPosition];//切换楼层隐藏pathView
                
                indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(-1000, 0, 40, 50);
                
                
                indoorMapScrollView.floor = floor;//设置寻路路线集合文件名
                [indoorMapScrollView.mapViewNew clearSubviews];
                UILabel * navLabe = [self.view viewWithTag:50];
                [navLabe removeFromSuperview];
                indoorMapScrollView.mapViewNew.floor = floor;//设置楼层设施文件路径
                [indoorMapScrollView.mapViewNew loadSVGFrom:[SampleFileInfo sampleFileInfoWithFilename:[NSString stringWithFormat:@"masp%@.svg",floor]].source rangeString:[NSString stringWithFormat:@"/masp%@.svg",floor]];//设置svg文件名
                [self getStoresNames:[NSString stringWithFormat:@"3"]];
                _floorButton.selected = NO;
                _floorView.hidden = YES;
                _addressView.hidden = YES;
            }
            
            
            
            
            //标记起点
            indoorMapScrollView.startUserPoint = CGPointMake(x, y);
            position.point = CGPointMake(x, y);
            if (indoorMapScrollView.mapViewNew.userImage &&(_endFloor == _currentFloor||(_endFloor != _currentFloor && _EndItem))) {
                //                    NSLog(@"--------%f===%f",x,y);
                float xx = x-20;
                float yy = y-50;
                if (x>0 && y>0) {
                    indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(xx, yy, 40, 50);
                    
                }
                //                    indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(105, 115, 40, 50);
                
                [indoorMapScrollView touchEndPosition];
            }
            
        }else if([locName isEqualToString:@"floor2"]){
            
            _currentFloor = 2;
            if (_endFloor !=_currentFloor) {
                _endFloor = 2;
                //切换二楼
                [_floorButton setTitle:@"2F" forState:UIControlStateNormal];
                NSString * floor = [NSString stringWithFormat:@"2"];
                
                indoorMapScrollView.endUserPoint = indoorMapScrollView.startUserPoint;
                indoorMapScrollView.mapViewNew.endImage.frame = CGRectMake(-1000, 0, 40, 50);
                [indoorMapScrollView touchEndPosition];//切换楼层隐藏pathView
                
                
                indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(-1000, 0, 40, 50);
                
                indoorMapScrollView.floor = floor;//设置寻路路线集合文件名
                [indoorMapScrollView.mapViewNew clearSubviews];
                UILabel * navLabe = [self.view viewWithTag:50];
                [navLabe removeFromSuperview];
                indoorMapScrollView.mapViewNew.floor = floor;//设置楼层设施文件路径
                [indoorMapScrollView.mapViewNew loadSVGFrom:[SampleFileInfo sampleFileInfoWithFilename:[NSString stringWithFormat:@"masp%@.svg",floor]].source rangeString:[NSString stringWithFormat:@"/masp%@.svg",floor]];//设置svg文件名
                [self getStoresNames:[NSString stringWithFormat:@"2"]];
                _floorButton.selected = NO;
                _floorView.hidden = YES;
                _addressView.hidden = YES;
            }
            
            
            
            
            //标记起点
            indoorMapScrollView.startUserPoint = CGPointMake(x, y);
            position.point = CGPointMake(x, y);
            if (indoorMapScrollView.mapViewNew.userImage &&(_endFloor == _currentFloor||(_endFloor != _currentFloor && _EndItem))) {
                //                    NSLog(@"--------%f===%f",x,y);
                float xx = x-20;
                float yy = y-50;
                if (x>0 && y>0) {
                    indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(xx, yy, 40, 50);
                    
                }
                //                    indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(105, 115, 40, 50);
                
                [indoorMapScrollView touchEndPosition];
            }
            
        }else if([locName isEqualToString:@"floor1"]){
            
            _currentFloor = 1;
            if (_endFloor !=_currentFloor) {
                _endFloor = 1;
                //切换二楼
                [_floorButton setTitle:@"1F" forState:UIControlStateNormal];
                NSString * floor = [NSString stringWithFormat:@"1"];
                
                indoorMapScrollView.endUserPoint = indoorMapScrollView.startUserPoint;
                indoorMapScrollView.mapViewNew.endImage.frame = CGRectMake(-1000, 0, 40, 50);
                [indoorMapScrollView touchEndPosition];//切换楼层隐藏pathView
                
                
                indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(-1000, 0, 40, 50);
                
                indoorMapScrollView.floor = floor;//设置寻路路线集合文件名
                [indoorMapScrollView.mapViewNew clearSubviews];
                UILabel * navLabe = [self.view viewWithTag:50];
                [navLabe removeFromSuperview];
                indoorMapScrollView.mapViewNew.floor = floor;//设置楼层设施文件路径
                [indoorMapScrollView.mapViewNew loadSVGFrom:[SampleFileInfo sampleFileInfoWithFilename:[NSString stringWithFormat:@"masp%@.svg",floor]].source rangeString:[NSString stringWithFormat:@"/masp%@.svg",floor]];//设置svg文件名
                [self getStoresNames:[NSString stringWithFormat:@"1"]];
                _floorButton.selected = NO;
                _floorView.hidden = YES;
                _addressView.hidden = YES;
            }
            
            
            
            
            //标记起点
            indoorMapScrollView.startUserPoint = CGPointMake(x, y);
            position.point = CGPointMake(x, y);
            if (indoorMapScrollView.mapViewNew.userImage &&(_endFloor == _currentFloor||(_endFloor != _currentFloor && _EndItem))) {
                //                    NSLog(@"--------%f===%f",x,y);
                float xx = x-20;
                float yy = y-50;
                if (x>0 && y>0) {
                    indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(xx, yy, 40, 50);
                    
                }
                //                    indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(105, 115, 40, 50);
                
                [indoorMapScrollView touchEndPosition];
            }
            
        }else if([locName isEqualToString:@"floor4"]){
            
            _currentFloor = 4;
            if (_endFloor !=_currentFloor) {
                _endFloor = 4;
                //切换二楼
                [_floorButton setTitle:@"4F" forState:UIControlStateNormal];
                NSString * floor = [NSString stringWithFormat:@"4"];
                
                indoorMapScrollView.endUserPoint = indoorMapScrollView.startUserPoint;
                indoorMapScrollView.mapViewNew.endImage.frame = CGRectMake(-1000, 0, 40, 50);
                [indoorMapScrollView touchEndPosition];//切换楼层隐藏pathView
                
                
                indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(-1000, 0, 40, 50);
                
                indoorMapScrollView.floor = floor;//设置寻路路线集合文件名
                [indoorMapScrollView.mapViewNew clearSubviews];
                UILabel * navLabe = [self.view viewWithTag:50];
                [navLabe removeFromSuperview];
                indoorMapScrollView.mapViewNew.floor = floor;//设置楼层设施文件路径
                [indoorMapScrollView.mapViewNew loadSVGFrom:[SampleFileInfo sampleFileInfoWithFilename:[NSString stringWithFormat:@"masp%@.svg",floor]].source rangeString:[NSString stringWithFormat:@"/masp%@.svg",floor]];//设置svg文件名
                [self getStoresNames:[NSString stringWithFormat:@"4"]];
                _floorButton.selected = NO;
                _floorView.hidden = YES;
                _addressView.hidden = YES;
            }
            
            
            
            
            //标记起点
            indoorMapScrollView.startUserPoint = CGPointMake(x, y);
            position.point = CGPointMake(x, y);
            if (indoorMapScrollView.mapViewNew.userImage &&(_endFloor == _currentFloor||(_endFloor != _currentFloor && _EndItem))) {
                //                    NSLog(@"--------%f===%f",x,y);
                float xx = x-20;
                float yy = y-50;
                if (x>0 && y>0) {
                    indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(xx, yy, 40, 50);
                    
                }
                //                    indoorMapScrollView.mapViewNew.userImage.frame = CGRectMake(105, 115, 40, 50);
                
                [indoorMapScrollView touchEndPosition];
            }
            
        }
        
        
    }else  if (tag == SX_SX_queryShopRankingMap) {
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
             [self hideKeyBoard];
            _storePointArray = database[@"result"];
            _floorOrFaciality = 3;
            [_tableView reloadData];
            _tableView.hidden = NO;
            _maskButton.hidden = NO;
         
        }
    }else if (tag==SX_SX_queryStoreNames){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSArray * array = database[@"result"];
            _storePointArray = array;
            [indoorMapScrollView.mapViewNew drawStoreNames:array];
            
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    //        [self dismissWaitDialog];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"havaNoFacilities" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"havaAddEndImage" object:nil];
}

@end
